package logic

import (
	"context"
	"fmt"
	"math/rand"
	"project/model/redis"
	"project/pkg"
	"strconv"
	"time"

	"project/projectrpc/internal/svc"
	"project/projectrpc/projectrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendSmsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSendSmsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendSmsLogic {
	return &SendSmsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SendSmsLogic) SendSms(in *projectrpc.SendSmsRequest) (*projectrpc.SendSmsResponse, error) {
	// todo: add your logic here and delete this line

	i := rand.Intn(9000) + 1000
	resp, err := pkg.SendSms(in.Tel, strconv.Itoa(i))
	if err != nil {
		return nil, fmt.Errorf("短信验证码获取失败")
	}
	if *resp.Body.Code != "OK" {
		return nil, fmt.Errorf(*resp.Body.Message)
	}

	redis.Rdb.Set("sendsms"+in.Source+in.Tel, i, time.Minute*1)

	NumKey := "sendsmsNum" + in.Source + in.Tel
	LocKey := "sendsmsLoc" + in.Source + in.Tel
	loc := redis.Rdb.Exists(LocKey).Val()
	if loc > 0 {
		return nil, fmt.Errorf("一小时以内只能发送5次短信")
	}
	redis.Rdb.Incr(NumKey)
	result, _ := redis.Rdb.Get(NumKey).Result()
	if result >= "5" {
		redis.Rdb.Set(LocKey, "1", time.Hour*1)
	}
	redis.Rdb.Expire(LocKey, time.Hour*1)

	return &projectrpc.SendSmsResponse{}, nil
}
